package com.icesoft.base.manager.security.login.handle;

import com.icesoft.base.manager.security.config.SecurityProperty;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.web.helper.RequestHold;
import com.icesoft.core.web.helper.ResponseUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@AllArgsConstructor
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {
    private SecurityProperty securityProperty;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException, IOException {
        log.trace("授权失败", authException);
        String msg = authException.getMessage();
        if (msg == null) {
            msg = "授权失败";
        }
        if (authException instanceof InsufficientAuthenticationException) {
            msg = "未登录";
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (RequestHold.isAjax(request)) {
            ResponseUtils.writeJson(response, Resp.error(msg).data(securityProperty.getLoginPage()));
        } else {
            String loginPage = securityProperty.getLoginPage();
            if (!"/".equals(request.getContextPath())) {
                loginPage = request.getContextPath() + loginPage;
            }
            response.sendRedirect(loginPage);
        }
    }
}
